#!/bin/bash

help() {
  echo "【数据中台-开发工具】"
  echo "  -s, --sql：执行SQL脚本（根据环境变量执行mysql或者瀚高脚本）"
  echo "      --sql       -e：执行SQL命令          示例：dp-tools --sql -e 'select * from table;'"
  echo "      --sql       -f：执行SQL文件          示例：dp-tools --sql -f test.sql"
  echo "  -h, --highgo：瀚高数据库工具"
  echo "      --highgo    -e：执行SQL语句          示例：dp-tools --highgo -e 'select * from table;'"
  echo "      --highgo    -f：执行SQL文件          示例：dp-tools --highgo -f test.sql"
  echo "  -c, --check：检测中间件、常见服务运行状态"
  echo "      --check     -r：检查redis运行状态     示例：dp-tools --check -r"
  exit 1
}

execute_sql() {
  log_message "执行SQL脚本，$@"
  case "$1" in
    -e)
      if [ "${DB_TYPE}" == 'mysql' ]; then
        /data/package/mysql/mysql -h mysql.ahcloud-private.com -P 3307 -umysql -p$MYSQL_PASSWD - e "$2"
      elif [ "${DB_TYPE}" == 'highgo' ]; then
        PGPASSWORD=${DB_PASSWORD} /lib64/psql -h highgo.ahcloud-private.com -p 5866 -U ${DB_USERNAME} -c "$2"
      fi
      ;;
    -f)
      if [ "${DB_TYPE}" == 'mysql' ]; then
        /data/package/mysql/mysql -h mysql.ahcloud-private.com -P 3307 -umysql -p$MYSQL_PASSWD < "$2"
      elif [ "${DB_TYPE}" == 'highgo' ]; then
        PGPASSWORD=${DB_PASSWORD} /lib64/psql -h highgo.ahcloud-private.com -p 5866 -U ${DB_USERNAME} -f "$2"
      fi
      ;;
    *)
      log_message "未知命令: $COMMAND"
      help
      ;;
  esac
}

highgo() {
  case "$1" in
    -e)
      PGPASSWORD=${DB_PASSWORD} /lib64/psql -h highgo.ahcloud-private.com -p 5866 -U ${DB_USERNAME} -c "$2"
      ;;
    -f)
      PGPASSWORD=${DB_PASSWORD} /lib64/psql -h highgo.ahcloud-private.com -p 5866 -U ${DB_USERNAME} -f "$2"
      ;;
    *)
      log_message "未知命令: $COMMAND"
      help
      ;;
  esac
}

check() {
  case "$1" in
    -r)
      redis-cli -res
      ;;
    *)
      log_message "未知命令: $COMMAND"
      help
      ;;
  esac
}

if [ $# -eq 0 ]; then
  help
fi

COMMAND=$1
shift  # 移除第一个参数（命令），剩下的参数传递给对应的函数
case "$COMMAND" in
  -s|--sql)
    execute_sql "$@"
    ;;
  -h|--highgo)
    highgo "$@"
    ;;
  -c|--check)
    check "$@"
    ;;
  help)
    usage
    ;;
  *)
    log_message "未知命令: $COMMAND"
    help
    ;;
esac